package handerls

import (
	"admin-pro/cache"
	"admin-pro/models"
	"admin-pro/pkg"
	"github.com/gin-gonic/gin"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账号或密码不能为空",
		})
		return
	}
	redis_key := "redis_log_" + username
	redisCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if redisCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录大于三次，禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if redisCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "登录已锁定，两小时后解锁",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账户或密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
	return
}
